<?php


namespace app\api\services;


use app\common\exception\ApiException;
use app\common\model\ClientModel;
use app\common\model\MessageLogModel;
use app\common\model\UserGroupModel;
use app\common\model\UserListModel;
use app\common\services\BaseService;
use push\Wxpusher;

class MessageService extends BaseService
{

    static public $wxPuhserToken = 'AT_3y2HFmfURwmLIPjx6HM8vb6JjHvCce3U';

    /**
     * 传入mid 简单判断是否是群组
     * @param $mid
     */
    static function isGroup($mid){
        return $mid<100000?1:0;
    }

    /**
     * 获取用户 与 另一个用户的消息记录
     */
    static function getMessageList($params){
        $uid = $params['uid'];
        $mid = $params['mid'];
        $is_group = self::isGroup($mid);//小于100w 则为群组;//小于100w 则为群组
        if($is_group){
            $where = [
                'to_user_id'=>$mid,
                'is_group'=>1,
            ];
        }else{
            $where = " is_group = 0 and (from_user_id = {$uid} and to_user_id = {$mid}) or (from_user_id = {$mid} and to_user_id = {$uid})";
        }
        $model = new MessageLogModel;
        $list = $model->where($where)->order('id desc')->paginate(10);
        $list = $list->toArray();
        $list['data'] = arraySort($list['data'],'id',SORT_ASC);

        //将消息标记为已读
        MessageLogModel::updates([
            'from_user_id'=>$mid,
            'to_user_id'=>$uid,
            'is_reda'=>1,
        ],['is_reda'=>2]);
        // 需要发送消息

        return $list;
    }

    /**
     * 发送聊天信息
     * @param $params [uid,mid,msg]
     * @param int $type 消息类型 1 文字 2 图片  3 系统消息  4 仅自己可见 5 系统消息，不补充人名  6 名片消息  7 文件
     * @return MessageLogModel|\think\Model
     * @throws ApiException
     */
    static function sendMessage($params,$type=1){
        $time = time();
        $u_info = ClientModel::findOne(['id'=>$params['uid']],'id,nickname,headimg');
        if(empty($u_info)){
            throw new ApiException('用户信息获取失败，请先登录');
        }
        $is_group = self::isGroup($params['mid']);//小于100w 则为群组

        //检查是否是好友 不是则不允许发消息
        $frinedStatus = ClientService::getStatus($params['uid'],$params['mid']);
        if($frinedStatus == 0){
            $msg = $is_group ? '您不在该群聊中，无法发送消息':'您还不是对方好友，无法发送消息';
            throw new ApiException($msg);
        }else if(!$is_group && $frinedStatus ==1){
            //群聊只需要单方面的好友  私聊才需要双方好友
            throw new ApiException('您还不是对方好友，无法发送消息');
        }else if($frinedStatus==2){
            throw new ApiException('您未添加对方为好友，无法发送消息');
        }

        //检查完毕

        $data = [
            'is_group'=>$is_group,
            'type'=>$type,
            'from_user_id'=>$params['uid'], //id
            'from_user_nickname'=>$u_info['nickname'],//昵称
            'from_user_headimg'=>$u_info['headimg'],//头像
            'to_user_id'=>$params['mid'],
            'msg'=>$params['msg'],
            'datetime'=>date('Y-m-d H:i:s'),
            'create_time'=>$time,
            'is_reda'=>1,//1 未读  2 已读
        ];
        $res = MessageLogModel::create($data);
        $data['id'] = $res['id'];
        //追加未读数量
        UserListService::addRedaNumber($params['uid'],$params['mid']);

        //做 websocket 消息推送
        if($res){
            $data['datetime'] = mdate2(strtotime($data['datetime']),1);
            GatewayService::toMessage($data);
        }

        // 做公众号消息推送
        self::wxPusher($data);

        return $res;
    }

    /**
     * 做公众号的消息推送
     */
    static function wxPusher($data){
        if($data['is_group']){
            $summary = "{$data['from_user_nickname']} 在群聊中说：{$data['msg']}";
        }else{
            $summary = "{$data['from_user_nickname']} 对您说：{$data['msg']}";
        }
        // 需要推送的目标
        $uidList = [];
        if($data['is_group']==1){
            //是群消息
            $uids = UserListModel::findAll(['mid'=>$data['to_user_id'],'type'=>2,'quiet'=>0],"uid");
            if(empty($uids)){
                return '';
            }
            $uids = array_column($uids,'uid');
            $client = ClientModel::findAll([['role','=',1],['id','in',$uids]],'id,wxpusher');
            $wxpusher = array_column($client,'wxpusher');
            $uidList = array_filter($wxpusher);
            $mid = $data['to_user_id'];
        }else{
            //个人消息
            $to_user_id = $data['to_user_id'];
            $u_info = ClientModel::findOne(['id'=>$to_user_id],'id,role,wxpusher');
            // 只对客服进行推送
            if($u_info['role']==2){
                return;
            }
            // 没有绑定推送的用户 不推送
            if(!$u_info['wxpusher']){
                return ;
            }
            $uidList[] = $u_info['wxpusher'];
            $mid = $data['from_user_id'];
        }
        // 没有需要推送的目标
        if(count($uidList)==0){
            return ;
        }
        //实例化
        $wx = new Wxpusher(self::$wxPuhserToken);
//        $wx->send('内容','摘要','类型','是否为用户id',id或数组id,'需传送的url',是否返回messageID))
        $messageId = $wx->send('您有新的聊天消息，可点击下方链接去查看',$summary,true,1,$uidList,'https://imserviceh5.hnbjsj.com/#/wechat/dialogue?mid='.$mid,false);
    }


    /**
     * 设置置顶 or 消息免打扰等
     */
    static function SetUp($params){
        $mid = $params['mid'];
        $field = $params['field'];
        $value = $params['value']?:0;//默认0
        if(!in_array($field,['quiet','is_top','is_show'])){
            return false;
        }
        if(strpos($mid,",")!==false){
            // 多个
            $where = "uid = {$params['uid']} and mid in ({$mid})";
        }else{
            // 单个
            $where = [
                'uid'=>$params['uid'],
                'mid'=>$mid,
            ];
        }
        return UserListModel::updates($where,[
           $field=>$value
        ]);
    }


}